# valueIterationAgents.py
# -----------------------
# Licensing Information:  You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).


# valueIterationAgents.py
# -----------------------
# Licensing Information:  You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).


import mdp, util

from learningAgents import ValueEstimationAgent
import collections

class ValueIterationAgent(ValueEstimationAgent):
    """
        * Please read learningAgents.py before reading this.*

        A ValueIterationAgent takes a Markov decision process
        (see mdp.py) on initialization and runs value iteration
        for a given number of iterations using the supplied
        discount factor.
    """
    def __init__(self, mdp: mdp.MarkovDecisionProcess, discount = 0.9, iterations = 100):
        """
          Your value iteration agent should take an mdp on
          construction, run the indicated number of iterations
          and then act according to the resulting policy.

          Some useful mdp methods you will use:
              mdp.getStates()
              mdp.getPossibleActions(state)
              mdp.getTransitionStatesAndProbs(state, action)
              mdp.getReward(state, action, nextState)
              mdp.isTerminal(state)
        """
        self.mdp = mdp
        self.discount = discount
        self.iterations = iterations
        self.values = util.Counter() # A Counter is a dict with default 0
        self.runValueIteration()

    def runValueIteration(self):
        """
          Run the value iteration algorithm. Note that in standard
          value iteration, V_k+1(...) depends on V_k(...)'s.
        """
        "*** YOUR CODE HERE ***"
        # states 初始 gui 状态
        states = self.mdp.getStates()

        # self.values 初始化
        for state in states:
            self.values[state] = {}
            self.values[state]["old"] = 0
            self.values[state]["new"] = 0

        # 获得新的 values
        def getNewValue(currentstate):
            # maxValue 通过比较各个动作选取最大的 value
            maxValue = float("-inf")
            # 获取当前状态所有可能的动作
            actions = self.mdp.getPossibleActions(currentstate)
            # 对于所有动作计算 value
            for action in actions:
                probabilitys = self.mdp.getTransitionStatesAndProbs(currentstate, action)
                value = 0
                # 将此动作所有的 概率得到的值相加
                for probability in probabilitys:
                    value += probability[1]*(self.mdp.getReward(currentstate, action, probability[0]) + self.discount*self.values[probability[0]]["old"])
                # 取最大值保存
                maxValue = max(maxValue, value)
                # if value > maxValue:
                #     maxValue = value
            return maxValue
        
        # 通过值迭代，迭代 self.iterations 次
        def performIteration(iterations):
            # 判断迭代次数
            if iterations >= self.iterations:
                return
            # 将每个 state 迭代一次
            for state in states[1:]:
                self.values[state]["new"] = getNewValue(state)
            
            # 将 旧的值替换为新的值
            for state in states[1:]:
                self.values[state]["old"] = self.values[state]["new"]

            # 查看错误用
            # print(iterations)
            # for state in states[1:]:
            #     print(state,round(self.values[state]["new"], 2))
            performIteration(iterations + 1)

        # 进行迭代
        performIteration(0)

        # 将 self.values 的值归一
        for k in self.values.keys():
            self.values[k] = self.values[k]["new"]
        
        # 网上看的答案(很奇怪)
        # for i in range(self.iterations):
        #     new_counter = util.Counter()
        #     for state in self.mdp.getStates():
        #         if not self.mdp.isTerminal(state):
        #             best_q = float("-inf")
        #         #找到最优选择即奖励值大的一个
        #         for action in self.mdp.getPossibleActions(state):
        #             curr_q = self.computeQValueFromValues(state, action)
        #             best_q = max(best_q, curr_q)
        #             new_counter[state] = best_q
        #             self.values = new_counter



    def getValue(self, state):
        """
          Return the value of the state (computed in __init__).
        """
        return self.values[state]

    def computeQValueFromValues(self, state, action):
        """
          Compute the Q-value of action in state from the
          value function stored in self.values.
        """
        "*** YOUR CODE HERE ***"
        #初值为0
        q = 0
        for probabilitys in self.mdp.getTransitionStatesAndProbs(state, action):
        #按照提示来的计算公式
            q += probabilitys[1] * (self.mdp.getReward(state, action, probabilitys[0]) + (self.discount * self.values[probabilitys[0]]))
        #返回 (state, action) 对应的 Q 值
        return q

    def computeActionFromValues(self, state):
        """
          The policy is the best action in the given state
          according to the values currently stored in self.values.

          You may break ties any way you see fit.  Note that if
          there are no legal actions, which is the case at the
          terminal state, you should return None.
        """
        "*** YOUR CODE HERE ***"
        actions = self.mdp.getPossibleActions(state)
        highValue = float("-inf")
        move = None
        for action in actions:
            currentQ = self.computeQValueFromValues(state, action)
            if currentQ > highValue:
                highValue = currentQ
                move = action
            # currV = self.values[self.mdp.getTransitionStatesAndProbs(state, action)[0][0]]
            # if currV > highValue:
            #     highValue = currV
            #     move = action
        return move

        # util.raiseNotDefined()

    def getPolicy(self, state):
        return self.computeActionFromValues(state)

    def getAction(self, state):
        "Returns the policy at the state (no exploration)."
        return self.computeActionFromValues(state)

    def getQValue(self, state, action):
        return self.computeQValueFromValues(state, action)
